package com.sunshine.lnuplus.internet

import com.sunshine.lnuplus.callback.LoadTitleCallBack
import com.sunshine.lnuplus.callback.LoginCallBack
import com.sunshine.lnuplus.service.LoadSchoolDateService
import com.sunshine.lnuplus.service.LoadWeatherService
import okhttp3.*
import org.json.JSONException
import org.jsoup.Jsoup
import java.io.IOException

class LoadTitle(
    private var callBack: LoadTitleCallBack
) {

    init {
        loadTitle()
    }

    private fun loadTitle() {
        val url = "http://www.iyuji.cn/iyuji/s/VUlpZG1WZ3A2alo2OWtxZThadHU2QT09/1584662484861635"
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {

            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                resolveTitle(response.body!!.string())
            }
        })
    }

    private fun resolveTitle(SchoolDataString: String) {
        try {
            val document = Jsoup.parse(SchoolDataString)
            val elements = document.select("p")
            val title = elements.toString().replace("<p>", "").replace("</p>", "")
            callBack.onSuccess(title)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }
}